package vip.wangwenhao.page;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author wangwenhao
 */
@AllArgsConstructor
@NoArgsConstructor
@Builder(builderMethodName = "pageBuilder", toBuilder = true)
public class BasePage implements Serializable {

    private static final long serialVersionUID = -4570922350645210375L;

    protected static final int MIN_PAGE     = 1;
    protected static final int MAX_PAGE     = Integer.MAX_VALUE;
    /** default:第1页 */
    protected static final int DEFAULT_PAGE = 1;

    protected static final int MIN_PAGE_SIZE     = 1;
    /** 用于不分页场景 */
    protected static final int MAX_PAGE_SIZE     = 100;
    /** default：每页20条 */
    protected static final int DEFAULT_PAGE_SIZE = 10;

    /** 默认查询页数和页码 */
    @Builder.Default
    private int page = DEFAULT_PAGE;
    @Builder.Default
    private int pageSize = DEFAULT_PAGE_SIZE;

    /** 默认查询总数 */
    @Builder.Default
    private boolean queryCount = true;

    /**
     * 当前页，分页时使用
     */
    public int getPage() {
        if (page < MIN_PAGE) {
            page = MIN_PAGE;
        } else if (page > MAX_PAGE) {
            page = MAX_PAGE;
        }
        return page;
    }

    public void setPage(int page) {
        if (page <= 0) {
            this.page = DEFAULT_PAGE;
        } else {
            this.page = page;
        }
    }

    public int getPageSize() {
        if (pageSize < MIN_PAGE_SIZE) {
            pageSize = DEFAULT_PAGE_SIZE;
        } else if (pageSize > MAX_PAGE_SIZE) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        if (pageSize <= 0) {
            this.pageSize = DEFAULT_PAGE_SIZE;
        } else {
            this.pageSize = pageSize;
        }
    }

    /**
     * 偏移量，分页时使用, 不可使用getPageSize方法代替pageSize，因为该方法被子类覆盖
     */
    public int getOffset() {
        if (page == 1) {
            return 0;
        }
        return pageSize * (page - 1);
    }

    /**
     * 偏移量，分页时使用, 不可使用getPageSize方法代替pageSize，因为该方法被子类覆盖
     */
    public int getStart() {
        if (page == 1) {
            return 0;
        }
        return pageSize * (page - 1) + 1;
    }

    public boolean isQueryCount() {
        return queryCount;
    }

    public void setQueryCount(boolean queryCount) {
        this.queryCount = queryCount;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("PageOption{");
        sb.append("page=").append(page);
        sb.append(", pageSize=").append(pageSize);
        sb.append(", queryCount=").append(queryCount);
        sb.append('}');
        return sb.toString();
    }
}
